package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.Util.CurrentUserContextHolders;
import com.qk.common.constants.BusinessStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.domain.business.BusinessDO;
import com.qk.domain.business.BusinessPoolDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.dto.business.BusinessPoolListDTO;
import com.qk.dto.business.UpdateBusinessDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author: zyx
 * @created: 2025-10-15-10:55
 * @description:
 */
@Slf4j
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public void add(BusinessDTO dto) {
        //参数校验
        if (ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getName())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        if(ObjectUtil.isEmpty(dto.getChannel())){
            CommonException.throwCommonException(ParamEnum.CHANNEL_NOT_NULL);
        }
        //补全参数
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.TO_BE_ALLOCATED);
        this.save(business);
    }

    @Override
    public PageResult<BusinessDO> selectPage(BusinessListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<BusinessDO> page = this.baseMapper.selectByPage(dto);
        return PageResult.<BusinessDO>builder()
                .total((int) page.getTotal()).rows(page.getResult()).build();
    }

    @Transactional
    @Override
    public void followUpBusiness(UpdateBusinessDTO dto) {
        //拿到商机基础信息拷贝到新的Business对象中
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setUpdateTime(LocalDateTime.now());
        if (Objects.equals(business.getStatus(), BusinessStatusConstants.TO_BE_FOLLOW_UP)) {
            business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        }
        this.updateById(business);
        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecord.setId(null);
        businessTrackRecord.setBusinessId(dto.getId());
        businessTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.businessTrackRecordMapper.insert(businessTrackRecord);
    }

    @Override
    public BusinessVO getBusinessInfoById(Integer id) {
        //查询商机基础信息
        Business business = this.baseMapper.selectById(id);
        String assignName = this.userMapper.getUserById(business.getUserId()).getUsername();
        //根据商机id查询跟进记录
        List<BusinessTrackRecord> businessTrackRecords = this.businessTrackRecordMapper.selectList(Wrappers.<BusinessTrackRecord>lambdaQuery().eq(BusinessTrackRecord::getBusinessId, id));
        //封装成VO对象并返回
        BusinessVO businessVO = BeanUtil.copyProperties(business, BusinessVO.class);
        List<BusinessVO.TrackRecordVO> list = businessTrackRecords.stream().map(item -> {
            BusinessVO.TrackRecordVO trackRecordVO = BeanUtil.copyProperties(item, BusinessVO.TrackRecordVO.class);
            trackRecordVO.setAssignName(assignName);
            return trackRecordVO;
        }).toList();
        businessVO.setTrackRecords(list);
        return businessVO;
    }

    @Transactional
    @Override
    public void toCustomer(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.TO_CUSTOMER);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);
        //组装客户信息并添加到数据库
        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setId( null);
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        customer.setBusinessId(id);
        this.customerMapper.insert(customer);
    }

    @Override
    public void backToSea(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.RECYCLED);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);
    }

    @Override
    public PageResult<BusinessPoolDO> poolPage(BusinessPoolListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<BusinessPoolDO> page = this.baseMapper.selectPoolPage(dto);
        return PageResult.<BusinessPoolDO>builder()
                .total((int) page.getTotal()).rows(page.getResult()).build();
    }
}
